package com.hhkj.study.admin.user.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hhkj.study.admin.course.entity.Course;
import com.hhkj.study.admin.course.entity.CourseAssocResourceStat;
import com.hhkj.study.admin.course.entity.CourseResourceInfo;
import com.hhkj.study.admin.course.enums.CourseAssocResourceTypeEnum;
import com.hhkj.study.admin.course.service.extend.CourseExtendService;
import com.hhkj.study.admin.resource.excel.ResourceQuestionBankExcelRes;
import com.hhkj.study.admin.resource.model.podo.ResourceCourseVideoPo;
import com.hhkj.study.admin.resource.service.extend.ResourceCourseVideoExtendService;
import com.hhkj.study.admin.user.model.podo.UserStatisticPo;
import com.hhkj.study.admin.user.model.req.UserCourseStatisticReq;
import com.hhkj.study.admin.user.model.req.UserStatisticExportReq;
import com.hhkj.study.admin.user.model.res.UserStatisticExcelRes;
import com.hhkj.study.admin.user.model.res.UserStatisticRes;
import com.hhkj.study.admin.user.service.base.UserListenService;
import com.hhkj.study.admin.user.service.biz.UserCourseBizService;
import com.hhkj.study.admin.user.service.biz.UserStatisticBizService;
import com.hhkj.study.api.user.model.res.ApiUserListenCourseRes;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.excl.utils.ExcelUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author luowu
 * @Date 2025/1/9 涵 14:51:00
 */
@Service
public class UserStatisticBizServiceImpl implements UserStatisticBizService {

    @Resource
    private UserListenService userListenService;

    @Resource
    private UserCourseBizService userCourseBizService;

    @Resource
    private CourseExtendService courseExtendService;

    @Resource
    private ResourceCourseVideoExtendService videoExtendService;

    @Override
    public List<UserStatisticRes> countUserCourse(UserCourseStatisticReq req) {
        List<UserStatisticPo> userStatisticList = userListenService.countUserStudyByCondition(req);
        if (CollectionUtil.isEmpty(userStatisticList)) {
            return Lists.newArrayList();
        }
        List<UserStatisticRes> userStatisticResList = BeanUtil.copyToList(userStatisticList, UserStatisticRes.class);
        List<Long> idList = userStatisticList.stream().map(UserStatisticPo::getId).collect(Collectors.toList());
        // 课程id不为空，则只统计该课程的总数据
        if (ObjectUtil.isEmpty(req.getCourseId())) {
            List<Course> courseList = courseExtendService.listByIdList(idList);
            if (CollectionUtil.isEmpty(courseList)) {
                return Lists.newArrayList();
            }
            Pair<Map<Long, String>, Map<Long, CourseAssocResourceStat>> courseMapPair
                    = processCourseResourceStat(courseList);
            // 用户课程学习情况统计 map集合
            List<ApiUserListenCourseRes> orderUserCourseStudyResList = userCourseBizService
                    .handlerOrderCourseListByOrderIdList(Lists.newArrayList(req.getOrderItemId()), req.getUserId());
            Map<Long, ApiUserListenCourseRes> userOrderCourseStudyResMap = orderUserCourseStudyResList.stream()
                    .collect(Collectors.toMap(ApiUserListenCourseRes::getCourseId, Function.identity()
                            , (o, d) -> {
                                d.setCount(d.getCount() + o.getCount());
                                return d;
                            }
                    ));
            userStatisticResList.forEach(userStatisticRes -> {
                String courseName = courseMapPair.getLeft().getOrDefault(userStatisticRes.getId(), "");
                userStatisticRes.setName(courseName);
                CourseAssocResourceStat courseAssocResourceStat = courseMapPair.getRight()
                        .getOrDefault(userStatisticRes.getId(), new CourseAssocResourceStat());
                ApiUserListenCourseRes userCourseListenRes = userOrderCourseStudyResMap
                        .getOrDefault(userStatisticRes.getId(), new ApiUserListenCourseRes());
                if (ObjectUtil.isEmpty(courseAssocResourceStat)) {
                    userStatisticRes.setStudyProgress("0");
                } else {
                    userStatisticRes.setLessonCount(courseAssocResourceStat.getResourceCount());
                    userStatisticRes.setStudyProgress(MathUtils.calculateThePercentage(userCourseListenRes.getCount()
                            , courseAssocResourceStat.getResourceCount()));
                }
            });
        } else {
            List<ResourceCourseVideoPo> resourceCourseVideoList = videoExtendService.listByIdList(idList);
            if (CollectionUtil.isEmpty(resourceCourseVideoList)) {
                return Lists.newArrayList();
            }
            Map<Long, String> videoNameMap = resourceCourseVideoList.stream()
                    .collect(Collectors.toMap(ResourceCourseVideoPo::getId, ResourceCourseVideoPo::getName));
            userStatisticResList.forEach(userStatisticRes -> {
                String videoName = videoNameMap.getOrDefault(userStatisticRes.getId(), "");
                userStatisticRes.setName(videoName);
            });
        }
        return userStatisticResList;
    }

    @Override
    public void exportUserStatistic(UserStatisticExportReq req, HttpServletResponse response) {
        List<UserStatisticExcelRes> userStatisticResList = userListenService.countUserStudyDetail(req);
        if (CollectionUtil.isEmpty(userStatisticResList)) {
            throw new GlobalException("没有查询到数据");
        }
        ExcelUtils.exportExcelRuoYi(response, BeanUtil.copyToList(userStatisticResList
                , UserStatisticExcelRes.class)
                , UserStatisticExcelRes.class, "用户学习数据统计", "用户学习数据统计");
    }

    private Pair<Map<Long, String>, Map<Long, CourseAssocResourceStat>> processCourseResourceStat(List<Course> courseList){
        if (CollectionUtil.isEmpty(courseList)) {
            return Pair.of(Maps.newHashMap(), Maps.newHashMap());
        }
        Map<Long, CourseAssocResourceStat> courseAssocResourceMap = courseList.stream()
                .collect(Collectors.toMap(Course::getId, course -> {
            List<CourseAssocResourceStat> courseAssocResourceStatList = Optional.of(course)
                    .map(Course::getAssocResourceStat)
                    .map(CourseResourceInfo::getCourseAssocResourceList)
                    .orElse(Lists.newArrayList());
            return courseAssocResourceStatList.stream().filter(e -> CourseAssocResourceTypeEnum.VIDEO.getCode()
                    .equals(e.getResourceType())).findFirst().orElse(new CourseAssocResourceStat());
        }));
        Map<Long, String> courseNameMap = courseList.stream().collect(Collectors.toMap(Course::getId, Course::getName));
        return Pair.of(courseNameMap, courseAssocResourceMap);
    }
}
